'use strict';
import React, { Component } from 'react';
import {
    View,
    Text,
    StyleSheet,
    Image,
    ListView,
    RefreshControl,
    ActivityIndicator,
    TouchableOpacity,
    Dimensions,
    Platform,
    Animated,
    TouchableHighlight,
    AsyncStorage,
    Alert,
    NativeModules
} from 'react-native';

import { connect } from 'react-redux';

import NavTitle from './NavTitle';
import BindUser from '../page/personal/BindUser';
import PersonalInfo from '../page/personal/PersonalInfo';
import RealEstateInfo from '../page/problem/RealEstateInfo';
import CommunityInfo from '../page/problem/CommunityInfo';

var windowWidth = Dimensions.get('window').width;
var circleHeight = Dimensions.get('window').height*0.66;
var circleRadius = (windowWidth-80)/2;

var dotArray = [];
for(var i = 0;i < 100; i++){
  dotArray.push(i);
}

function gen32LenStr() {//生成唯一key值
    var guid = "";
    for (var i = 1; i <= 32; i++) {
        var n = Math.floor(Math.random() * 16.0).toString(16);
        guid += n;
        if (i == 20) {
            guid += "";
        }
    }
    return guid;
}

class Status extends Component {
    constructor(props){
        super(props);
        this.state={
            dotOpticy:dotArray.map(ele => {
              return new Animated.Value(0);
            })
        };
    }

    componentDidMount() {
      for(var i = 0;i<this.props.score;i++){
        Animated.timing(this.state.dotOpticy[i], {   //开始从隐藏到显示的动画
          toValue: 1,
          duration:500,
          delay:30*i
        }).start()
      }
    }

    _showScore(){
        var lineScores = [];
        let _nowDeg = 120;
        for(var i = 0;i<this.props.score;i++){
            if(i !== 0){
              _nowDeg = _nowDeg + 3;
            }
            lineScores.push(
              <Animated.View
                key={gen32LenStr()}
                style={[styles.scoreDot,{
                  transform:[{
                    rotateZ:_nowDeg +'deg'
                  },{
                    translateX:circleRadius
                  }],
                  opacity:this.state.dotOpticy[i]
                }]}>
              </Animated.View>
            )
        }
        return lineScores;
    }

    _showHideScore(){
        var lineScores = [];
        let _nowDeg = 120;
        for(var i = 0;i<100;i++){
            if(i !== 0){
              _nowDeg = _nowDeg + 3;
            }
            lineScores.push(
              <View
                key={"scoreHideDot"+i}
                style={[styles.scoreHideDot,{
                  transform:[{
                    rotateZ:_nowDeg +'deg'
                  },{
                    translateX:circleRadius
                  }]
                }]}>
              </View>
            )
        }
        return lineScores;
    }

    componentWillReceiveProps(nextProps){
        if(this.props.score !== nextProps.score){
          this.setState({
              dotOpticy:dotArray.map(ele => {
                return new Animated.Value(0);
              })
          })
        }
    }

    componentDidUpdate(){
      for(var i = 0;i<this.props.score;i++){
        Animated.timing(this.state.dotOpticy[i], {   //开始从隐藏到显示的动画
          toValue: 1,
          duration:500,
          delay:30*i
        }).start()
      }
    }

    _pressSet() {
      if(!this.props.loginStatus) {
        this.props.navigator.push({
            component: BindUser,
            name: 'BindUser'
        });
      } else {
        this.props.navigator.push({
            component: PersonalInfo,
            name: 'PersonalInfo'
        });
      }
    }

    render(){
        const {navigator} = this.props;

        let _component = null;

        if(80 < this.props.score && this.props.score <= 100){
            _component = require('../imgs/status100.png');
        }else if(70 < this.props.score && this.props.score <= 80){
            _component = require('../imgs/status80.png');
        }else{
            _component = require('../imgs/status70.png');
        }

        return(
          <Image source={_component} style={styles.topImage}>
              <NavTitle
                  leftButton={true}
                  headColor = {'rgba(0,0,0,0)'}
                  leftImg={require('../imgs/setting.png')}
                  barColor={'#18B5C8'}
                  leftHander={() => this._pressSet() }
              />
              <View style={styles.topHead}>
                  {this._showHideScore()}
                  {this._showScore()}
                  <Image source={require('../imgs/circle.png')} style={styles.circleCcore}>
                      <Text style={styles.circleText}>{this.props.score}</Text>
                  </Image>
              </View>
              {this.props.score == 100 &&
                  <View style={styles.textStatus}>
                      <Text style={styles.statusText}>最佳状态</Text>
                  </View>
              }
              {this.props.score != 100 &&
                  <View style={styles.buttonStatus}>
                    {this.props.repairCount != 0 &&
                      <TouchableOpacity
                          onPress={() => {
                            navigator.push({
                                component: CommunityInfo,
                                name: 'CommunityInfo',
                                params: {
                                  readOnly: true,
                                  type: 3
                                }
                            });
                          }}>
                          <Text style={styles.statusText}>{this.props.repairCount}个报修</Text>
                      </TouchableOpacity>
                    }
                    {this.props.complaintCount != 0 &&
                      <TouchableOpacity
                           style={{marginLeft:20}}
                           onPress={() => {
                             navigator.push({
                                 component: RealEstateInfo,
                                 name: 'RealEstateInfo',
                                 params: {
                                   readOnly: true,
                                   type: 3
                                 }
                             });
                           }} >
                          <Text style={styles.statusText}>{this.props.complaintCount}个投诉</Text>
                      </TouchableOpacity>
                    }
                  </View>
              }
          </Image>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flexDirection: 'column',
        backgroundColor: '#F5F5F5',
        flex: 1,
    },
    topImage:{
        height:circleHeight,
        flexDirection:'column',
        width: windowWidth
    },
    topHead:{
        position:'relative',
        height:circleHeight/1.66
    },
    circleCcore:{
      position:'absolute',
      top:circleHeight/3,
      left:Dimensions.get('window').width/2,
      width:windowWidth-120,
      height:windowWidth-120,
      marginLeft:-(windowWidth-120)/2,
      marginTop:-(windowWidth-120)/2,
      alignItems:'center',
      justifyContent:'center',
      backgroundColor:'rgba(0,0,0,0)',
    },
    circleText:{
        fontSize:86,
        color:'#FFF'
    },
    scoreDot:{
        position:'absolute',
        top:circleHeight/3,
        left:Dimensions.get('window').width/2,
        width:10,
        height:2,
        marginLeft:-5,
        backgroundColor:'#FFF',
        borderRadius:1
    },
    scoreHideDot:{
      position:'absolute',
      top:circleHeight/3,
      left:Dimensions.get('window').width/2,
      width:10,
      height:2,
      marginLeft:-5,
      backgroundColor:'rgba(255,255,255,.2)',
      borderRadius:1
    },
    textStatus:{
      flex:1,
      marginTop:10,
      backgroundColor:'rgba(0,0,0,0)',
      alignItems:'center',
      justifyContent:'center',
    },
    buttonStatus:{
      flex:1,
      marginTop:10,
      backgroundColor:'rgba(0,0,0,0)',
      flexDirection: 'row',
      alignItems:'center',
      justifyContent:'center',
    },
    statusText:{
      justifyContent:'center',
      alignSelf:'center',
      fontSize:18,
      color:'#FFF'
    }
});

const mapStateToProps = (state) => {
  return {
    score: state.cycle.score,
    repairCount: state.cycle.repairCount,
    complaintCount: state.cycle.complaintCount,
    loginStatus: state.login.loginStatus
  }
}

export default connect(
  mapStateToProps
)(Status)
